package com.cx.common.util;

import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author flysand
 * @package com.cx.common.util
 * @date 2021-11-07 19:15
 * @des JedisUtils: jedis单连接
 */
public class JedisUtils {

    private static String host;
    private static int port;
    private static String password;

    private static Jedis jedis;

    static {
        Properties properties = new Properties();
        InputStream is = JedisUtils.class.getClassLoader().getResourceAsStream("config/redis.properties");
        try {
            properties.load(is);
            host = properties.getProperty("redis.host");
            port = Integer.parseInt(properties.getProperty("redis.port"));
            password = properties.getProperty("redis.password");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 连接redis
     *
     * @return jedis连接
     */
    public static Jedis connRedis() {
        jedis = new Jedis(host, port);
        if (StringUtils.isNotBlank(password)) {
            jedis.auth(password);
        }
        jedis.connect();
        return jedis;
    }

    public static void closeConn(){
        if (jedis != null){
            jedis.close();
        }
    }
}
